<?php

namespace App\Http\Controllers\Open;

use App\Http\Controllers\Traits\ResourceController;
use App\Http\Controllers\Controller;
use Illuminate\Auth\Events\Registered;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;
use App\Models\GpsadvUsers;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Validator;
use App\Facades\ClientAuth;
use Illuminate\Support\Facades\Redis;
class GpsadvRegisterController extends Controller
{
    use ResourceController;
//
//    public function __construct()
//    {
//        $this->middleware('guest');
//    }

    /**
     * 资源模型
     * @var  string
     */
    protected $resourceModel = 'GpsadvUser';

//    /**
//     * 验证规则
//     * @return    array
//     */
//    protected function getValidateRule($id=0)
//    {
//        return $this->getImportValidateRule($id,Request::all());
//    }

//    /**
//     * 验证规则
//     * @return  array
//     */
//    protected function getImportValidateRule($id = 0, $item){
//        $validate = ['status'=>'nullable|in:0,1,2','mobile_phone'=>'sometimes|required|mobile_phone|unique:users,mobile_phone,'.$id.',id,deleted_at,NULL'];
//        return $validate;
//    }

//    /**
//    * 编辑页面数据返回处理
//    * @param  $id
//    * @param  $data
//    * @return  mixed
//    */
//    protected function handleEditReturn($id,&$data){
//        return $data;
//    }
    /**
     * @param string $resourceModel
     */
    public function __construct()
    {
        Validator::extend('isValidAndroidId', function ($attribute, $value, $parameters, $validator) {
            if($attribute == "android_id"){
                return $this->isValidAndroidId($value);
            }else{
                return false;
            }
        });
    }
    //检测是否为正确的android id
    public function isValidAndroidId($value){

        return (preg_match('/^[0-9a-z+\/]+={0,2}$/i', $value) === 1)&&(strlen($value) == 16);
    }

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(\Illuminate\Http\Request $request)
    {
        $validator = [
            'android_id'=>'required|isValidAndroidId:gpsadv_users,android_id'
        ];

        return Validator::make($request->all(), $validator, [
//            'android_id.unique' => trans('The android id has already been registered!'),//'手机号已被使用了',
            'android_id.required' => trans('The android id is Required!'),//'手机号已被使用了',
            "android_id.isValidAndroidId"=> trans('The android id is not valided!')
        ]);
    }


    /**
     * 手机用户注册
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function register(\Illuminate\Http\Request $request)
    {
        Log::info('register: {input}', ['input' => $request->all()]);
        $validator = $this->validator($request);
        if ($validator->fails()) {
            $error_msg = $validator->errors()->first();
            return Response::returns([
                'errors' => 1,
                'message' => $error_msg
            ], 422);
        }
        $data = $request->all();
        $data['status']=1;
        $data['user_client_id']=ClientAuth::getClient();
        try {
            $user = GpsadvUsers::where('android_id',$data['android_id'])->first();
            Log::info('register: {$user}', ['$user' => $user]);
            if($user){
                $user->user_client_id = $data['user_client_id'];
                $user->save();
            }else{
                $user = GpsadvUsers::create($data);
            }


        }catch (\Exception $e){
            return Response::returns([
                'errors' => 1,//注册成功
                'message' => trans('registration failded').$e->getMessage()
            ],422);
        }

        Redis::Hset("android_id-client_id",$data['android_id'],$data["user_client_id"]);

        Redis::hset("client_id-android_id",$data["user_client_id"],$data['android_id']);

        return Response::returns([
            'errors' => 0,//注册成功
            'message' => trans('Registered successfully!'),
            "data"=>$user->id
        ],200);

//        $model = $this->caseType(); //模式
//        $model_name = Arr::get($this->map,$model); //模式名称
//        //最后验证短信码
//        $validator = Validator::make($request->all(), [
//            'message_code' => 'required|send_code:'.$model.','.config($this->send_code_key)
//        ], [
//            'message_code.send_code' => $model_name=='邮箱'?trans('Email verification code verification failed!'):trans('SMS verification code verification failed!')
//        ]);
//        if ($validator->fails()) {
//            return Response::returns([
//                'errors' => $validator->errors()->toArray(),
//                'message' => trans('The given data was invalid.')
//            ], 422);
//        }
//        $data = $request->all();
//        $data['status'] = 1;
//        $data['uname'] = $data['username'];
//        event(new Registered($user = User::create($data)));
//        $this->bindOuser($user);
//        if(config('laravel_admin.register_login')){
//            Auth::guard()->login($user);
//            return $this->sendLoginResponse($request);
//        }else{
//            return Response::returns([
//                'alert' => alert(['message' => trans('Registered successfully!')]),//注册成功
//                'redirect' => $this->redirectAfterLogout
//            ],200);
//        }

    }


}
